import { getCollection } from '@/service/collection';
import { AddUserParams, IUser, UpdateUserParams } from '@/service/types';
import { pick, rest } from 'lodash-es';

export const userCollection = getCollection<IUser>('uni-id-users');

const fields = ['username', 'nickname', 'role', 'email', 'mobile', 'email', 'status', 'password', 'dcloud_appid', 'tags'];

const getFields = `${fields.filter((item) => item !== 'password').join(',')},register_date,last_login_date,last_login_ip`;

const existUser = async (username: string) => {
	try {
		const res = await userCollection.where({ username }).count();
		return res.total > 0;
	} catch (error) {
		throw error;
	}
};
const existAdmin = async () => {
	try {
		const db = uniCloud.database();
		let countRes = await db.collection('uni-id-users').where({ role: 'admin' }).count();
		let count = countRes.result.total;
		return count > 0;
	} catch (error) {
		throw error;
	}
};

const existUserById = async (id: string) => {
	try {
		const res = await userCollection.where({ _id: id }).count();
		return res.total > 0;
	} catch (error) {
		throw error;
	}
};
const getAllUser = async () => {
	try {
		const res = await userCollection.field(getFields).get();
		return res.data;
	} catch (error) {
		throw error;
	}
};

const getPaginationUser = async (params: PaginationParams) => {
	try {
		const res = await userCollection
			.where(params.query ? params.query : {})
			.field(getFields)
			.limit(params.limit)
			.skip(params.skip)
			.get({ getCount: true });
		return res;
	} catch (error) {
		throw error;
	}
};
const addUser = async (data: AddUserParams) => {
	try {
		const exist = await existUser(data.username);
		if (exist) {
			throw new Error('用户已存在');
		}

		const pickData = pick(data, fields);

		const res = await userCollection.add(pickData);
		return res.id;
	} catch (error) {
		throw error;
	}
};

const updateUser = async (data: UpdateUserParams) => {
	const exist = await existUserById(data._id);
	if (!exist) {
		throw new Error('用户不存在');
	}
	const pickData = pick(data, fields);
	console.log(pickData);
	try {
		const res = await userCollection
			.where({
				_id: data._id,
			})
			.update(pickData);
		return res.updated;
	} catch (error) {
		throw error;
	}
};

const deleteUser = async (id: string) => {
	try {
		const res = await userCollection.where({ _id: id }).remove();
		return res.deleted;
	} catch (error) {
		throw error;
	}
};

const getUserInfo = async () => {
	try {
		let res = await userCollection.where('_id==$cloudEnv_uid').field('username,nickname,mobile,email,role,permission').getOne();
		return res.data;
	} catch (error) {
		throw error;
	}
};

export const user = {
	getAllUser,
	addUser,
	updateUser,
	getPaginationUser,
	deleteUser,
	existAdmin,
	getUserInfo,
};
